package io.renren.api;

import java.util.concurrent.Future;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import io.renren.entity.UserEntity;
import io.renren.task.AsyncTask;
import io.renren.utils.R;
import io.renren.utils.annotation.IgnoreAuth;
import io.renren.utils.annotation.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * API测试接口
 *
 */
@RestController
@RequestMapping("/api")
@Api("测试接口")
public class ApiTestController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private AsyncTask asyncTask;

    /**
     * 获取用户信息
     */
    @GetMapping("userInfo")
    @ApiOperation(value = "获取用户信息")
    @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true)
    public R userInfo(@LoginUser UserEntity user){
        return R.ok().put("user", user);
    }

    /**
     * 忽略Token验证测试
     */
    @IgnoreAuth
    @GetMapping("notToken")
    @ApiOperation(value = "忽略Token验证测试")
    public R notToken(){
        return R.ok().put("msg", "无需token也能访问。。。");
    }
    
    /**
	 * 测试异步方法调用顺序
	 */
    @IgnoreAuth
	@ApiOperation(value="测试异步方法调用顺序", notes="getEntityById")
    @RequestMapping(value = "/getTestDemoAsync", method = RequestMethod.GET)
	public @ResponseBody R getEntityById() throws Exception {
    	
		long start = System.currentTimeMillis();

		Future<String> task1 = asyncTask.doTaskOne();
		Future<String> task2 = asyncTask.doTaskTwo();
		Future<String> task3 = asyncTask.doTaskThree();

		while(true) {
			if(task1.isDone() && task2.isDone() && task3.isDone()) {
				// 三个任务都调用完成，退出循环等待
				break;
			}
			Thread.sleep(1000);
		}

		long end = System.currentTimeMillis();

		logger.info("任务全部完成，总耗时：" + (end - start) + "毫秒");
		
		
		return R.ok().put("msg", "测试异步任务成功");
	}
}
